package com.czy.workflow.core.context;

import com.czy.workflow.core.executor.TaskExecutor;
import com.czy.workflow.core.listener.TaskListenerNotify;
import com.czy.workflow.core.service.FlowService;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.logging.Logger;

/**
 * Created by admin on 2019/8/31.
 */
public class FlowContext {

    private final static Logger logger = Logger.getLogger(FlowContext.class.toString());

    private Map<String, Object> executorList = new HashMap<>();
    private Map<String, Method> executorMethodList = new HashMap<>();
    private Map<String, FlowService> flowServiceImplMap = new HashMap<>();

    private FlowConfig flowConfig;

    private ExecutorService threadPoolService;

    private TaskListenerNotify taskListenerNotify;

    private TaskExecutor taskExecutor;

    private FlowService flowService;

    public FlowContext(FlowConfig flowConfig, TaskExecutor taskExecutor,  ExecutorService threadPoolService, TaskListenerNotify taskListenerNotify, FlowService flowService) {
        this.flowConfig = flowConfig;
        this.taskExecutor = taskExecutor;
        this.threadPoolService = threadPoolService;
        this.taskListenerNotify = taskListenerNotify;
        this.flowService = flowService;
    }

    public boolean addExecutor(String flowCode, Object bean){
        executorList.put(flowCode, bean);
        return true;
    }

    public boolean addMethod(String flowCode, String nodeCode, Method method){
        String key = key(flowCode, nodeCode);
        boolean exist = executorMethodList.containsKey(key);
        executorMethodList.put(key, method);
        return exist;
    }

    public boolean addFlowService(String name, FlowService bean){
        flowServiceImplMap.put(name, bean);
        return true;
    }

    public Object getExecutor(String flowCode){
        return executorList.get(flowCode);
    }

    public Method getMethod(String flowCode, String nodeCode){
        String key = key(flowCode, nodeCode);
        return executorMethodList.get(key);
    }

    public TaskExecutor getTaskExecutor(){
        return this.taskExecutor;
    }

    public TaskListenerNotify getTaskListenerNotify(){
        return this.taskListenerNotify;
    }

    public ExecutorService getThreadPoolService(){
        return this.threadPoolService;
    }

    public FlowService getFlowService() {
        return this.flowService;
    }

    public FlowConfig getFlowConfig(){
        return this.flowConfig;
    }


    public Collection<Method> getExecutorMethodList(){
        return executorMethodList.values();
    }

    private String key(String code1, String code2){
        return code1 + "." + code2;
    }
}
